import 'webext-dynamic-content-scripts';
import addDomainPermissionToggle from 'webext-permission-toggle';

export const enum StorageKey {
  ColorsDisabled = 'colorsDisabled',
  DarkMode = 'darkMode',
}

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'change-icon-color',
    title: 'Change icon colors',
    contexts: ['action'],
  });

  chrome.contextMenus.create({
    id: 'toggle-dark-mode',
    title: 'Toggle dark mode',
    contexts: ['action'],
  });

  addDomainPermissionToggle();
});

const toggleStorage = (key: StorageKey) => (tabs: chrome.tabs.Tab[]) => {
  const activeTab = tabs[0];

  chrome.storage.sync.get(key, (storage) => {
    chrome.storage.sync.set({ [key]: !storage[key] }, () => {
      if (activeTab.id !== undefined) {
        chrome.tabs.reload(activeTab.id);
      }
    });
  });
};

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'change-icon-color') {
    chrome.tabs.query(
      {
        active: true,
        currentWindow: true,
      },
      toggleStorage(StorageKey.ColorsDisabled),
    );
  } else if (info.menuItemId === 'toggle-dark-mode') {
    // Special handling for GitCode theme toggle
    if (tab && tab.url && tab.url.includes('gitcode.com') && tab.id) {
      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => {
          // Toggle GitCode theme by modifying data-theme attribute
          const html = document.documentElement;
          const currentTheme = html.getAttribute('data-theme');
          const newTheme = currentTheme === 'black' ? 'light' : 'black';
          
          console.log('GitCode: Toggling theme from', currentTheme, 'to', newTheme);
          html.setAttribute('data-theme', newTheme);
          
          // Also update body if it has data-theme
          const body = document.body;
          if (body.hasAttribute('data-theme')) {
            body.setAttribute('data-theme', newTheme);
          }
          
          // Trigger a custom event to notify the content script
          window.dispatchEvent(new CustomEvent('gitcode-theme-changed', {
            detail: { theme: newTheme }
          }));
          
          // Update extension storage to match
          chrome.storage.sync.set({ darkMode: newTheme === 'black' });
        }
      });
    } else {
      // For other sites, use the original toggle behavior
      chrome.tabs.query(
        {
          active: true,
          currentWindow: true,
        },
        toggleStorage(StorageKey.DarkMode),
      );
    }
  }
});

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo?.status === 'complete' && tab?.url) {
    try {
      const url = new URL(tab.url);
      if (url.hostname === 'gitcode.com' || url.hostname === 'github.com') {
        chrome.tabs.sendMessage(tabId, {
          message: 'file-icon-extension-page-update',
        });
      }
    } catch (error) {
      // 忽略無效的 URL
      console.warn('Invalid URL:', tab.url);
    }
  }
});
